package com.Policing.Fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Check.Check_Item;
import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.Policing.Adapter.Check_adapter;
import com.Policing.Check.Check_choose;
import com.Policing.Ip_set.Ip_Set;

import com.Policing.R;
import com.Policing.bean.fragmentfor_bean;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 */

public class Fragment4 extends Fragment {
    private ImageView imageView,screen;
    private ListView listVie;
    private SlideSideMenuExampleActivity mainActivity;
    public Context context;
    private TextView title_text;
    private  WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private List<Map<String, Object>> underway = new ArrayList<Map<String, Object>>();//待盘点
    private List<Map<String, Object>> Have_inventory = new ArrayList<Map<String, Object>>();//已盘点
    private List<Map<String, Object>> For_inventory = new ArrayList<Map<String, Object>>();//待盘点
    private String url="http://"+ Ip_Set.IP+"/api/checkQuery";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second4,null);
        return view;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        context=getActivity();
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        Log.i("ipipip",Ip_Set.IP);
        init();

        if (context!=null){
            mainActivity = (SlideSideMenuExampleActivity) getActivity();
          //  lv.add("21123");
          //  lv.add("211");
         //   Map<String, Object> map = new HashMap<String, Object>();
            //   map.put("assetName",userList.get(i).getCheckId());
            //   map.put("assetNumber",userList.get(i).getPlanUser());
          //  map.put("assetName","22");
         //   map.put("assetNumber","22");
          //  list.add(map);
        //    Reception_Adapter re_ad = new Reception_Adapter(context,list);
          // // listView.setAdapter(re_ad);
            listVie= (ListView) getActivity().findViewById(R.id.checklist);
          //  listVie.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1,lv));
            Timer timer=new Timer();//实例化Timer类
            timer.schedule(new TimerTask(){
                public void run(){
                    load();
                    this.cancel();
                }
            },200);//五百毫秒
            listVie.setOnItemClickListener((parent, view, i, id) -> {
                String str = String.valueOf(listVie.getAdapter().getItem(i));
                String[] strs=str.split(",");
                if (strs[0].toString().contains("不")){
                    Log.e("数据", strs[1]);
                    Intent intent = new Intent(mainActivity, Check_Item.class);
                    intent.putExtra("checkId",strs[1].toString());
                   // intent.putExtra("status",strs[0].toString());
                    startActivity(intent);
                }else {
                    Log.e("数据1", strs[1]);
                    Intent intent = new Intent(mainActivity, Check_choose.class);
                    intent.putExtra("checkId",strs[1].toString());
                   // intent.putExtra("status",strs[0].toString());
                    startActivity(intent);
                }

            });


        }


    }

    private void load() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    FormBody.Builder body = new FormBody.Builder();
                    body.add("source", Since_case.set().getSource());
                    Request request = new Request.Builder()
                            .url(url)
                            .post(body.build())
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("2222222",responseData);
                    showResponse(responseData);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }




    private void showResponse(final String responseData) {
            mainActivity.runOnUiThread(() -> {
                list.clear();
                mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                if (responseData.equals("[]")){

                    Toast.makeText(mainActivity,"无盘点单",Toast.LENGTH_SHORT).show();
                    return;
                }

                Gson gson = new Gson();
                List<fragmentfor_bean> userList = gson.fromJson(responseData, new TypeToken<List<fragmentfor_bean>>(){}.getType());
                for(int i = 0;i < userList.size();i++){
                    Map<String, Object> map = new HashMap<String, Object>();
                   map.put("odd",userList.get(i).getCheckId());
                   map.put("Date_created",userList.get(i).getCreatedate().substring(0,10));
                    map.put("creator",userList.get(i).getCreateuser());
                    map.put("sum",userList.get(i).getNum());
                    if (userList.get(i).getDate().equals("")){
                        map.put("Inventory_date",userList.get(i).getDate());
                    }else
                    map.put("Inventory_date",userList.get(i).getDate().substring(0,10));
                    map.put("scope",userList.get(i).getRange());
                    map.put("state",userList.get(i).getStatus());
                    list.add(map);
                    Collections.reverse(list);
                }
                Check_adapter re_ad = new Check_adapter(context,list);
                listVie.setAdapter(re_ad);
            });
    }



    private void init() {
        screen = (ImageView) mainActivity.findViewById(R.id.screen);
        title_text = (TextView) mainActivity.findViewById(R.id.title_text);
        title_text.setText("盘点");
        screen.setOnClickListener(v -> new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"已盘点", "待盘点","进行中"}, mainActivity, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position==0){
                    //适配器，刚刚重写的！
                    Check_adapter re_ad = new Check_adapter(mainActivity,list);
                    listVie.setAdapter(re_ad);
                }
                if (position==1){
                    Have_inventory.clear();
                    for (int i = 0;i<list.size();i++){
                        if (list.get(i).get("state").equals("已盘点")){
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd",list.get(i).get("odd"));
                            map.put("Date_created",list.get(i).get("Date_created"));
                            map.put("creator",list.get(i).get("creator"));
                            map.put("sum",list.get(i).get("sum"));
                            map.put("Inventory_date",list.get(i).get("Inventory_date"));
                            map.put("scope",list.get(i).get("scope"));
                            map.put("state",list.get(i).get("state"));
                            Have_inventory.add(map);
                        }
                    }
                    Check_adapter re_ad = new Check_adapter(mainActivity,Have_inventory);
                    listVie.setAdapter(re_ad);

                }
                if (position==2){
                    For_inventory.clear();
                    for (int i = 0;i<list.size();i++){
                        if (list.get(i).get("state").equals("待盘点")){
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd",list.get(i).get("odd"));
                            map.put("Date_created",list.get(i).get("Date_created"));
                            map.put("creator",list.get(i).get("creator"));
                            map.put("sum",list.get(i).get("sum"));
                            map.put("Inventory_date",list.get(i).get("Inventory_date"));
                            map.put("scope",list.get(i).get("scope"));
                            map.put("state",list.get(i).get("state"));
                            For_inventory.add(map);
                        }
                    }
                    Check_adapter re_ad = new Check_adapter(mainActivity,For_inventory);
                    listVie.setAdapter(re_ad);

                }
                if (position==3){
                    underway.clear();
                    for (int i = 0;i<list.size();i++){
                        if (list.get(i).get("state").equals("进行中")){
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd",list.get(i).get("odd"));
                            map.put("Date_created",list.get(i).get("Date_created"));
                            map.put("creator",list.get(i).get("creator"));
                            map.put("sum",list.get(i).get("sum"));
                            map.put("Inventory_date",list.get(i).get("Inventory_date"));
                            map.put("scope",list.get(i).get("scope"));
                            map.put("state",list.get(i).get("state"));
                            underway.add(map);
                        }
                    }
                    underway.toString();
                    Check_adapter re_ad = new Check_adapter(mainActivity,underway);
                    listVie.setAdapter(re_ad);

                }

            }
        }).show());
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener(v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
            
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                //模拟3秒的加载过程
                new Handler().postDelayed(() -> {
                    load();//接下来可以刷新ListView
                }, 1200);

            }

        });

    }

    @Override
    public void onStart() {
        Timer timer=new Timer();//实例化Timer类
        timer.schedule(new TimerTask(){
            public void run(){
                load();
                this.cancel();
            }
        },300);//五百毫秒
        super.onStart();
    }


}
